import { useState, useMemo } from 'react';
import { usePortfolio } from '../context/PortfolioContext';
import WorkForm from '../components/WorkForm';
import WorkStats from '../components/WorkStats';
import DataManager from '../components/DataManager';
import Pagination from '../components/Pagination';
import CourseForm from '../components/CourseForm';

const Admin = () => {
  const { 
    isAdmin, 
    currentAdmin,
    adminPassword, 
    setAdminPassword, 
    handleAdminLogin, 
    allWorks: works, 
    deleteWork,
    openEditModal,
    loading,
    error,
    courses,
    deleteCourse,
    openCourseModal,
    loadWorks
  } = usePortfolio();
  const [loginError, setLoginError] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(null);
  const [username, setUsername] = useState('');
  const [activeTab, setActiveTab] = useState('works'); // 'works' 或 'courses'
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  
  // 计算分页数据
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedWorks = works.slice(startIndex, endIndex);
    const totalPages = Math.ceil(works.length / itemsPerPage);
    
    return {
      works: paginatedWorks,
      totalPages,
      totalItems: works.length
    };
  }, [works, currentPage, itemsPerPage]);
  
  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
    // 滚动到表格顶部
    document.querySelector('.bg-white.dark\\:bg-gray-800.rounded-lg.shadow')?.scrollIntoView({ 
      behavior: 'smooth', 
      block: 'start' 
    });
  };
  
  // 处理每页显示数量变化
  const handleItemsPerPageChange = (newItemsPerPage) => {
    setItemsPerPage(newItemsPerPage);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理管理员登录
  const handleLogin = async (e) => {
    e.preventDefault();
    const success = await handleAdminLogin(username, adminPassword);
    if (!success) {
      setLoginError('用户名或密码错误，请重试');
    } else {
      setLoginError('');
    }
  };

  // 处理删除作品
  const handleDelete = async (id, title) => {
    if (!window.confirm(`确定要删除作品"${title}"吗？此操作不可恢复。`)) {
      return;
    }

    try {
      setDeleteLoading(id);
      await deleteWork(id);
    } catch (err) {
      alert('删除失败，请重试');
    } finally {
      setDeleteLoading(null);
    }
  };

  // 处理删除课程
  const handleDeleteCourse = async (id, name) => {
    if (!window.confirm(`确定要删除课程"${name}"吗？此操作不可恢复。`)) {
      return;
    }

    try {
      setDeleteLoading(id);
      await deleteCourse(id);
    } catch (err) {
      alert('删除失败，请重试');
    } finally {
      setDeleteLoading(null);
    }
  };

  // 如果未登录，显示登录表单
  if (!isAdmin) {
    return (
      <div className="max-w-md mx-auto mt-12 bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
        <h2 className="text-2xl font-bold mb-4">管理员登录</h2>
        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="block mb-1">用户名</label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block mb-1">密码</label>
            <input
              type="password"
              value={adminPassword}
              onChange={(e) => setAdminPassword(e.target.value)}
              required
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          {loginError && (
            <p className="text-red-500 text-sm">{loginError}</p>
          )}
          <button
            type="submit"
            className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors"
          >
            登录
          </button>
        </form>
      </div>
    );
  }

  // 已登录，显示管理界面
  return (
    <div className="mt-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <div>
          <h2 className="text-2xl font-semibold">管理后台</h2>
          <p className="text-gray-600 dark:text-gray-400">欢迎，{currentAdmin?.username}</p>
        </div>
      </div>

      {/* 标签页导航 */}
      <div className="mb-6">
        <div className="border-b border-gray-200 dark:border-gray-700">
          <nav className="-mb-px flex space-x-8">
            <button
              onClick={() => setActiveTab('works')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'works'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              }`}
            >
              作品管理
            </button>
            <button
              onClick={() => setActiveTab('courses')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'courses'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              }`}
            >
              课程管理
            </button>
          </nav>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
          <p className="text-red-600 dark:text-red-400">{error}</p>
        </div>
      )}

      {/* 作品管理标签页 */}
      {activeTab === 'works' && (
        <div>
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
            <h3 className="text-xl font-semibold">作品管理</h3>
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-500 dark:text-gray-400">每页显示:</label>
                <select
                  value={itemsPerPage}
                  onChange={(e) => handleItemsPerPageChange(Number(e.target.value))}
                  className="px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value={5}>5</option>
                  <option value={10}>10</option>
                  <option value={20}>20</option>
                  <option value={50}>50</option>
                </select>
              </div>
              <div className="text-sm text-gray-500 dark:text-gray-400">
                共 {works.length} 个作品
              </div>
            </div>
          </div>

          {/* 统计信息 */}
          <WorkStats />
          
          {/* 数据管理 */}
          <div className="mb-8">
            <DataManager />
          </div>

          {/* 添加新作品表单 */}
          <div className="mb-8">
            <WorkForm isNew={true} />
          </div>

          {/* 编辑作品模态框 */}
          <WorkForm isNew={false} />

          {/* 作品列表 */}
          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
              <p className="mt-2 text-gray-500 dark:text-gray-400">加载中...</p>
            </div>
          ) : (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
              <div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        ID
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        封面
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        标题
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        创作者
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        分类
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        创建时间
                      </th>
                      <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        操作
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {paginatedData.works.map(work => (
                      <tr key={work.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                          {work.id}
                        </td>
                        <td className="py-4 px-4">
                          <img 
                            src={work.coverUrl} 
                            alt={work.title}
                            className="w-12 h-12 object-cover rounded"
                            onError={(e) => {
                              e.target.src = 'https://via.placeholder.com/48x48?text=No+Image';
                            }}
                          />
                        </td>
                        <td className="py-4 px-4">
                          <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {work.title}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 line-clamp-1">
                            {work.description}
                          </div>
                        </td>
                        <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                          {work.creator}
                        </td>
                        <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                          {work.category || '未分类'}
                        </td>
                        <td className="py-4 px-4 text-sm text-gray-500 dark:text-gray-400">
                          {work.createdAt ? new Date(work.createdAt).toLocaleDateString('zh-CN') : '-'}
                        </td>
                        <td className="py-4 px-4 text-sm">
                          <div className="flex gap-2">
                            <button
                              onClick={() => {
                                console.log('Opening edit modal for work:', work);
                                openEditModal(work);
                              }}
                              className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
                            >
                              编辑
                            </button>
                            <button
                              onClick={() => handleDelete(work.id, work.title)}
                              disabled={deleteLoading === work.id}
                              className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 transition-colors disabled:opacity-50"
                            >
                              {deleteLoading === work.id ? '删除中...' : '删除'}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              {works.length === 0 && (
                <div className="text-center py-8">
                  <p className="text-gray-500 dark:text-gray-400">暂无作品数据</p>
                </div>
              )}
              
              {/* 分页组件 */}
              {works.length > 0 && (
                <div className="px-4 pb-4">
                  <Pagination
                    currentPage={currentPage}
                    totalPages={paginatedData.totalPages}
                    totalItems={paginatedData.totalItems}
                    itemsPerPage={itemsPerPage}
                    onPageChange={handlePageChange}
                  />
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* 课程管理标签页 */}
      {activeTab === 'courses' && (
        <div>
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
            <h3 className="text-xl font-semibold">课程管理</h3>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              共 {courses.length} 个课程
            </div>
          </div>

          {/* 添加新课程表单 */}
          <div className="mb-8">
            <CourseForm isNew={true} />
          </div>

          {/* 编辑课程模态框 */}
          <CourseForm isNew={false} />

          {/* 课程列表 */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
            <div className="overflow-x-auto">
              <table className="min-w-full">
                <thead className="bg-gray-50 dark:bg-gray-700">
                  <tr>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      ID
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      封面
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      课程名称
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      任课教师
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      作品数量
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      创建时间
                    </th>
                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {courses.map(course => (
                    <tr key={course.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                      <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                        {course.id}
                      </td>
                      <td className="py-4 px-4">
                        <img 
                          src={course.coverImage || 'https://via.placeholder.com/48x48?text=课程'} 
                          alt={course.name}
                          className="w-12 h-12 object-cover rounded"
                          onError={(e) => {
                            e.target.src = 'https://via.placeholder.com/48x48?text=课程';
                          }}
                        />
                      </td>
                      <td className="py-4 px-4">
                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                          {course.name}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400 line-clamp-1">
                          {course.description}
                        </div>
                      </td>
                      <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                        {course.teacher}
                      </td>
                      <td className="py-4 px-4 text-sm text-gray-900 dark:text-gray-100">
                        {course.worksCount || 0}
                      </td>
                      <td className="py-4 px-4 text-sm text-gray-500 dark:text-gray-400">
                        {course.createdAt ? new Date(course.createdAt).toLocaleDateString('zh-CN') : '-'}
                      </td>
                      <td className="py-4 px-4 text-sm">
                        <div className="flex gap-2">
                          <button
                            onClick={() => {
                              // 跳转到作品展示页面，显示该课程的作品
                              window.open(`/works?courseId=${course.id}&courseName=${encodeURIComponent(course.name)}`, '_blank');
                            }}
                            className="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 transition-colors"
                          >
                            查看作品
                          </button>
                          <button
                            onClick={() => openCourseModal(course)}
                            className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
                          >
                            编辑
                          </button>
                          <button
                            onClick={() => handleDeleteCourse(course.id, course.name)}
                            disabled={deleteLoading === course.id}
                            className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 transition-colors disabled:opacity-50"
                          >
                            {deleteLoading === course.id ? '删除中...' : '删除'}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            
            {courses.length === 0 && (
              <div className="text-center py-8">
                <p className="text-gray-500 dark:text-gray-400">暂无课程数据</p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default Admin;
